<?php
class LRApi_transfer
{
	var $payees = array();

	function LRApiTransfer ($lrAccount, $apiName, $secretWord, $payees = array())
	{
		$this->call = new LRApi ($lrAccount, $apiName, $secretWord);
		$this->payees = $payees;
	}

	function execute()
	{
		$authXml = $this->call->AuthXml();

		$payees = $this->payees;

		$xml = '<TransferRequest id="' . $this->call->id . '">' . $authXml;

		foreach ($payees as $payee)
		{
			$payee->payerAcct = $this->call->lrAccount;
			$xml .= $payee->toXml();
		}

		$xml .=	'</TransferRequest>';

		$response = $this->call->getResponse("https://api.libertyreserve.com/xml/transfer.aspx?req=", $xml);

		if ($response != "")
		return $this->parseResponse ($response);
		else return "";
	}

	function parseResponse ($responseXml)
	{
		$response = array();

		$doc = new DOMDocument();
		if (!$doc->loadXML($responseXml))
		{
			$error = "Can't parse server's XML response.";
			return $response;
		}

		$rootElem = $doc->getElementsByTagName("TransferResponse")->item(0);
		$responseId = $rootElem->getAttribute("id");

		if ($responseId != $this->call->id)
		{
			$error = "ResponseId does not match RequestId.";
			return $response;
		}

		$payees = $this->payees;
		$counter = 0;

		$childElems = $rootElem->getElementsByTagName("*");

		for ($ci = 0; $ci < $childElems->length;  $ci++)
		{
			$elem = $childElems->item($ci);

			if ($elem->tagName == "Receipt" || $elem->tagName == "Error")
			{
				if ($elem->tagName == "Receipt")
				{
					$receipt = array();

					$receipt['ReceiptId'] = trim($elem->getElementsByTagName("ReceiptId")->item(0)->textContent);
					$receipt['Amount'] = trim($elem->getElementsByTagName("Amount")->item(0)->textContent);
					$receipt['Fee'] = trim($elem->getElementsByTagName("Fee")->item(0)->textContent);
					$receipt['ClosingBalance'] = trim($elem->getElementsByTagName("ClosingBalance")->item(0)->textContent);

					$response[$counter]['Transfer'] = $payees[$counter];
					$response[$counter]['Receipt'] = $receipt;

				}
				else if ($elem->tagName == "Error")
				{
					$error = array();

					$error['Code'] = trim($elem->getElementsByTagName("Code")->item(0)->textContent);
					$error['Text'] = trim($elem->getElementsByTagName("Text")->item(0)->textContent);

					$response[$counter]['Transfer'] = $payees[$counter];
					$response[$counter]['Error'] = $error;
				}

				$counter++;
			}
		}

		return $response;
	}
}